package com.naiterui.ehp.bp.support.filter;

import java.util.List;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户token处理 校验并解析token，将对应的用户Id参数放置于request parameter中
 *
 * @author guoyongxiang
 * @version 1.0.0
 * @date 2021/8/12 09:29
 **/
@Slf4j
@Data
public abstract class UserTokenHandler {

    private static PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 用户ID参数名
     */
    private String userIdKey;

    /**
     * 用户ID参数值
     */
    private String userIdValue;

    /**
     * 不进行token验证的路径列表
     */
    private List<String> excludePaths;

    protected UserTokenHandler(String userIdKey, List<String> excludePaths) {
        this.userIdKey = userIdKey;
        this.excludePaths = excludePaths;
    }

    /**
     * 获取并校验用户ID 该方法需要实现类覆盖
     *
     * @return
     */
    public abstract boolean checkToken(String token);

    public boolean ignorePath(String reqUrl) {
        if (excludePaths != null) {
            return excludePaths.stream().anyMatch(uri -> this.matchUrl(uri, reqUrl));
        }
        return true;
    }

    private boolean matchUrl(String matchUrl, String reqUrl) {
        return pathMatcher.match(matchUrl, reqUrl);
    }
}
